#include "stm32f10x.h"    
#include "freertos.h"
#include "task.h"
#include "queue.h"
#include "Delay.h"
#include "PC13_test.h"

#include "USART_Config.h"
#include "ESP01s_Control.h"

#include <string.h>

#define QUEUE_LENGTH 16	 				// 队列长度
#define ITEM_SIZE sizeof(USART_Message)	// 队列项大小
QueueHandle_t xQueue;

void vTask_ESP01s_Controller(void *arg);
void vTask_USART_Handler(void *arg);
void vReceiverTask(void *pvParameters);

int main(void){
	Delay_Init();						// 初始化 Delay函数
	
	USART_Pin_Init(&USART1_Cfg);  		// 初始化 USB_TO_TTL
	USART_NVIC_Init(&USART1_Cfg);  		// 初始化 中断源优先级
	
//	xQueue = xQueueCreate(QUEUE_LENGTH,  ITEM_SIZE);
	xQueue = xQueueCreate(QUEUE_LENGTH,  ITEM_SIZE);
	
	USART_SendString(&USART1_Cfg, "AT\r\n");  		// 测试1：测试串口发送功能，已通过
	
//	xTaskCreate(vTask_USART_Handler, "vTask_UART_Handler", configMINIMAL_STACK_SIZE * 4, NULL, 1, NULL); 		// 启动调度程序	
	xTaskCreate(vTask_ESP01s_Controller, "vTask_LED_Controller", configMINIMAL_STACK_SIZE * 4, NULL, 1, NULL);		// 串口任务优先级更低
 	vTaskStartScheduler();					// 启动调度器
	
	while(1);								// 程序不应执行到这里
}



//// 串口任务（专注指令接收）
//void vTask_USART_Handler(void *arg) {
//	USART1_printf(
//		"=== LED Controller ===\r\n"
//		"COMMANDS:\r\n"
//		"  OFF\\r    - Power off LED\r\n"
//		"  ON\\r     - Power on LED\r\n"
//		"  BLINK\\r  - Start blinking\r\n"
//		"-----------------------\r\n"
//		"Waiting for input...\r\n"
//	);
//	
//    while(1);
//}

// USART1控制任务
void vTask_ESP01s_Controller(void *arg) {	
	USART_Message msg;
	
    while(1) {		
		if(xQueueReceive(xQueue, &msg, 1000) == pdPASS){	// 写portMAX_DELAY会被持续阻塞
			switch(msg.source_id){
				case 1: 	USART_printf(&USART1_Cfg, "Receive the str: %s \r\n", (msg.data));	break;
				case 2: 	USART_printf(&USART2_Cfg, "Receive the str: %s \r\n", (msg.data));	break;
				case 3: 	USART_printf(&USART3_Cfg, "Receive the str: %s \r\n", (msg.data));	break;
			}

//			LED_Control(str); 
		}else{
			USART_printf(&USART1_Cfg, "Not receive now \r\n");
		}
		
		vTaskDelay(1000);
	}
}
